<?php
namespace app\index\controller;


use app\common\controller\Apicommon;
use app\index\model\Device;
use app\index\model\Door;
use think\Db;

class Gear extends Apicommon
{
    public function initialize()
    {
//        parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
        // 安全校验
        if(empty(session('user_auth.uid'))){
            $this->redirect(url('index/index/login'));
        }else{
            $this->uid = session('user_auth.uid');
        }
    }

    public function gear_list()
    {
        $where = [];
        $iris_id = input('iris_id');
        if (!empty($iris_id)){
            $where[] = ['iris_id','eq',$iris_id];
        }
        $gear = Db::name('gear')->where($where)->order('gear_serial','asc')->paginate(input('limit',10))->each(function ($item) {
            $item['iris'] = Db::name('iris')->where('id',$item['iris_id'])->value('iris_serial');
            return $item;
        });
        $iris = Db::name('iris')->order('iris_serial','asc')->field('id,iris_serial')->select();
        $this->assign('iris',$iris);
        $this->assign('pages',$gear->render());
        $this->assign('gear',$gear->items());
        return $this->fetch();
    }

    public function gear_add()
    {
        if ($_POST){
            $serial = input('serial');
            $model = input('model');
            $address = input('address');
            $iris_id = input('iris_id');
            $door_num = input('door_num');
            if (empty($serial) || empty($model) || empty($address) || empty($iris_id)|| empty($door_num)){
                return $this->ajaxReturn(1,'必填项未填');
            }
            // 检查柜体编号是否大于最大可计入柜体数量（6个）
            if ($serial > 6) {
                return $this->ajaxReturn(1,'柜子编号大于最大可接入柜子数量（6个）');
            }

            $check = db('gear')->where('gear_serial',$serial)->find();
            if (!empty($check)) {
                return $this->ajaxReturn(1,$serial . '号柜子已存在，请更改编号');
            }
            $gear_id = Db::name('gear')->insertGetId([
                'gear_serial' => $serial,
                'gear_model' => $model,
                'address' => $address,
                'iris_id' => $iris_id
            ]);
            if ($gear_id) {
                // 创建指定个数柜门
                for ($i = 1; $i <= $door_num; $i++) {
                    Door::create([
                        'door_serial' => $i,
                        'gear_id' => $gear_id,
                        'status' => 1,
                        'lock_status' => 0,
                        'is_security' => 0,
                    ]);
                }
                return $this->ajaxReturn(0, '新增成功');
            }
            return $this->ajaxReturn(1,'新增失败');
        }
        $iris = Db::name('iris')->field('id,iris_serial')->select();
        $this->assign('iris',$iris);
        return $this->fetch();
    }

    public function gear_edit($id = null)
    {
        $id = $id ?: input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        if ($_POST){
            $serial = input('serial');
            $model = input('model');
            $address = input('address');
            $iris_id = input('iris_id');
            if (empty($serial) || empty($model) || empty($address) || empty($iris_id)){
                return $this->ajaxReturn(1,'必填项未填');
            }
            $res = Db::name('gear')->where('id',$id)->update([
                'gear_serial'=>$serial,
                'model'=>$model,
                'address'=>$address,
                'iris_id'=>$iris_id
            ]);
            if ($res){
                return $this->ajaxReturn(0,'新增成功');
            }
            return $this->ajaxReturn(1,'新增失败');
        }
        $iris = Db::name('iris')->field('id,iris_serial')->select();
        $gear = Db::name('gear')->where('id',$id)->find();
        $this->assign('iris',$iris);
        $this->assign('gear',$gear);
        return $this->fetch();
    }

    public function gear_del()
    {
        $id = input('id');
        if (empty($id)){
            return $this->ajaxReturn(1,'缺少参数');
        }
        $ids = explode(',',$id);
        // 查询柜门
        $door = Door::whereIn('gear_id',$ids)->column('id');
        if (!empty($door)) {
            // 查询设备
            $device = Device::whereIn('door_id',array_values($door))->count('id');
            if (!empty($device)) {
                return $this->ajaxReturn(1,'该柜子还有'.intval($device).'个设备，不能删除');
            }
            Door::whereIn('gear_id',$ids)->delete();
        }
        $res = Db::name('gear')->whereIn('id',$ids)->delete();
        if ($res){
            return $this->ajaxReturn(0,'删除成功');
        }
        return $this->ajaxReturn(1,'删除失败');
    }
}